package com.itheima.entry;

import com.itheima.user.controller.IUserController;
import com.itheima.domain.User;
import com.itheima.factory.Factory;
import com.itheima.student.controller.IStudentController;
import com.itheima.student.controller.Impl.StudentControllerImpl;
import jdk.swing.interop.SwingInterOpUtils;

import java.io.*;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;

public class Entry {

    private static IUserController iChangeController;


    static Scanner sc = new Scanner(System.in);
    static {
        try {
            iChangeController = Factory.getIUserController();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static IStudentController iStudentController;

    static {
        try {
            iStudentController = Factory.getIStudentController();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public Entry() throws Exception {
    }

    public static void main(String[] args) throws Exception {
        entryMethod();
        return;
    }

    public static void entryMethod() throws Exception {
        LocalDateTime time = null;
        //IChangeController iChangeController = Factory.iChangeController();
        iChangeController.read();
        //Scanner sc = new Scanner(System.in);
        LocalDateTime newTime = getNewTime();//调用
        DateTimeFormatter pattern = null;
        try {
            pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
            String readStr = readTime();//读解锁时间
            newTime = LocalDateTime.parse(readStr, pattern);//解析
        } catch (Exception e) {
            newTime = getNewTime();
        }

        //读count
        int count = 0;
        try {
            FileReader fr = new FileReader("system\\message\\CountDenglu.txt");
            String countStr = (char)fr.read()+"";//转换
            count = Integer.parseInt(countStr);
        } catch (Exception e) {
            count = 0;
        }

        while (true) {
            System.out.println("<------------------欢迎------------------->");
            System.out.println("请输入您的选择1.登录  2.注册  3.忘记密码  4.查看日志  5.退出");
            String num = sc.next();
            lo:switch (num) {
                case "1":
                        /*if (count==3) {
                            FileWriter fw1 = new FileWriter("system\\message\\TwentyMData.txt");
                            fw1.write("1");
                            fw1.close();
                        }*/


                    LocalDateTime minute = LocalDateTime.now();
                    //int minute = now.getMinute();
                    if (count >= 3) {
                        if (Duration.between(minute, newTime).toSeconds() > 0) {
                            long between = Duration.between(minute, newTime).toSeconds();
                            System.out.println("登陆次数上限,请" + between / 60 + "分" + (between - between / 60 * 60) + "秒后重试");
                            break;    //跳出分支,不执行下面
                        } else {
                            count = 0;  //20分过了,次数从0开始

                        }
                    }
                    if (lign(time)) {   //登录成功,次数从0开始
                        count = 0;
                    } else {
                        count++;
                        System.out.println("用了" + count + "还剩" + (3 - count) + "次");
                        if (count>=3){
                            newTime = getNewTime();//次数用完之后开始获取20分钟
                        }
                    }
                    break;
                case "2":
                    iChangeController.addUser();
                    break;
                case "3":
                    System.out.println("请输入账号");
                    String username = sc.next();
                    ArrayList<User> allUser = iChangeController.findAllUser();
                    for (int i = 0; i < allUser.size(); i++) {
                        if (username.equals(allUser.get(i).getUsername())){
                            iChangeController.updatePassword(username);
                            break lo;
                        }
                    }
                    System.out.println("账户不存在");
                    if (allUser.size()==0){
                        System.out.println("账户不存在");
                    }
                    break;
                case "4":
                    findRiZhi();
                    //创建字符缓冲输入流
                    /*BufferedReader br = new BufferedReader(new  FileReader("system\\message\\Time.txt"));
                    String line;
                    while ((line=br.readLine())!=null) {
                        System.out.println(line);
                    }
                    br.close();*/
                    break;
                case "5"://退出
                    //存日志记录
                    LocalDateTime now = LocalDateTime.now();
                    String data = now.format(pattern);
                    String zhuceTime = data + "系统关闭";
                    FileWriter fw2 = new FileWriter("system\\message\\time\\tuiTime.txt", true);
                    fw2.write(zhuceTime);
                    fw2.write("\r\n");
                    fw2.close();
                    //存解锁时间
                    //newTime = getNewTime();
                    String format = newTime.format(pattern);//20分钟之后字符串格式
                    FileWriter fw = new FileWriter("system\\message\\TwentyMData.txt");
                    fw.write(format);//将解锁时间存进去
                    fw.close();
                    //存count
                    FileWriter fwCount = new FileWriter("system\\message\\CountDenglu.txt");
                    fwCount.write(count+"");
                    fwCount.close();
                    iChangeController.write();
                    System.exit(0);
                default:
                    System.out.println("输入有误,请重新输入");
                    break;
            }
        }
    }

    private static void findRiZhi() throws IOException {
        lo:while (true) {
            System.out.println("--------------------------------查看日志--------------------------------");
            System.out.println("请输入您的选择 1.注册时间  2.登录时间   3.退出系统时间   4.导出数据时间  5.退出");
            String choose = sc.next();
            switch (choose){
                case "1":
                    BufferedReader br = new BufferedReader(new  FileReader("system\\message\\time\\zhuceTime.txt"));
                    String line;
                    while ((line=br.readLine())!=null) {
                        System.out.println(line);
                    }
                    br.close();
                    break;
                case "2":
                    BufferedReader br2 = new BufferedReader(new  FileReader("system\\message\\time\\dengluTime.txt"));
                    String line2;
                    while ((line2=br2.readLine())!=null) {
                        System.out.println(line2);
                    }
                    br2.close();
                    break;
                case "3":
                    BufferedReader br3 = new BufferedReader(new  FileReader("system\\message\\time\\tuiTime.txt"));
                    String line3;
                    while ((line3=br3.readLine())!=null) {
                        System.out.println(line3);
                    }
                    br3.close();
                    break;
                case "4":
                    BufferedReader br4 = new BufferedReader(new  FileReader("system\\message\\time\\daoTime.txt"));
                    String line4;
                    while ((line4=br4.readLine())!=null) {
                        System.out.println(line4);
                    }
                    br4.close();
                    break;
                case "5":
                    System.out.println("感谢");
                    break lo;
                default:
                    System.out.println("输入有误");
                    break;
            }
        }
    }

    //du解锁时间
    public static String readTime() throws IOException {
        FileReader fr = new FileReader("system\\message\\TwentyMData.txt");
        StringBuilder sb = new StringBuilder();
        char[] chs = new char[1024];
        int len;
        while ((len = fr.read(chs)) != -1) {
            sb.append(new String(chs, 0, len));
        }
        return sb.toString();
        //System.out.println(data);
    }

    private static LocalDateTime getNewTime() {
        LocalDateTime time = LocalDateTime.now();
        //int minute = time.getMinute();
        LocalDateTime newTime = time.plusMinutes(20);
        //LocalDateTime newTime = time.plusMinutes(2);
        return newTime;
    }

    public static boolean lign(LocalDateTime time) throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入账号");
        String username = sc.next();
        System.out.println("请输入密码");
        String password = sc.next();
        Random ra = new Random();
        int ranum1 = ra.nextInt(100) + 1;
        int ranum2 = ra.nextInt(100) + 1;
        String sum = (ranum1 + ranum2) + "";
        System.out.println(ranum1 + "+" + ranum2 + "= ?");
        String newsum = sc.next();
        if (sum.equals(newsum)) {
            ArrayList<User> list = iChangeController.findAllUser();
            if (list.size() != 0) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getUsername().equals(username) && list.get(i).getPassword().equals(password)) {
                        System.out.println("登陆成功");

                        /*FileReader fr = new FileReader("system\\message\\Data.txt");
                        char[] chs = new char[1024];
                        int len;
                        while ((len = fr.read(chs)) != -1) {
                            System.out.println(new String(chs, 0, len));
                        }
                        fr.close();*/
                        for (int i1 = 0; i1 < list.size(); i1++) {
                            if (username.equals(list.get(i).getUsername())){
                                if (list.get(i).getDengluTime()!=null) {
                                    System.out.print("上次登录的时间:");
                                    System.out.println(list.get(i).getDengluTime());
                                    break;
                                }
                            }
                        }
                        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
                        time = LocalDateTime.now();
                        String data = time.format(pattern);
                        String s = "用户" + username + "于" + data + "登录了系统";
                        //日志
                        FileWriter fw = new FileWriter("system\\message\\time\\dengluTime.txt", true);
                        fw.write(s);
                        fw.write("\r\n");
                        fw.close();

                        for (int i1 = 0; i1 < list.size(); i1++) {
                            if (username.equals(list.get(i).getUsername())){
                                list.get(i).setDengluTime(s);
                            }
                        }
                        //合并代码,登陆成功进入管理系统
                        /*Choose choose = new Choose();
                        choose.*/
                        choose(username);
                        return true;
                    }
                }
                System.out.println("账号或密码有误");
            } else {
                System.out.println("账号或密码有误");
            }
        } else {
            System.out.println("验证码有误");
        }
        return false;
    }

    //合并代码,进入系统
    public static void choose(String usename) throws Exception {
        //IChangeController iChangeController = Factory.iChangeController();
        //IStudentController iStudentController = new StudentControllerImpl();
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("1.账号管理  2.信息管理  3.退出");
            String num = sc.next();
            switch (num) {
                case "1":
                    iChangeController.start(usename);
                    break;
                case "2":
                    iStudentController.start(usename);
                    break;
                case "3":
                    return;
                default:
                    System.out.println("输入有误,请重新输入");
                    break;
            }
        }
    }
}